<template>
  <div class="new-task">
    <el-card>
      <template #header>
        <span>发布新任务</span>
      </template>
      
      <el-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskRules"
        label-width="100px"
        class="task-form"
      >
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="taskForm.title" placeholder="请输入任务标题" />
        </el-form-item>
        
        <el-form-item label="任务描述" prop="description">
          <el-input
            v-model="taskForm.description"
            type="textarea"
            :rows="4"
            placeholder="请详细描述任务内容"
          />
        </el-form-item>
        
        <el-form-item label="奖励金额" prop="reward">
          <el-input-number
            v-model="taskForm.reward"
            :min="0"
            :precision="2"
            placeholder="请输入奖励金额"
            @change="calculateFees"
          />
          <div class="fee-info" v-if="taskForm.reward > 0">
            <p class="fee-item">
              <span>任务奖励：</span>
              <span class="amount">¥{{ taskForm.reward.toFixed(2) }}</span>
            </p>
            <p class="fee-item">
              <span>平台手续费（3%）：</span>
              <span class="fee">¥{{ platformFee.toFixed(2) }}</span>
            </p>
            <p class="fee-item total">
              <span>实际支付：</span>
              <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
            </p>
            <p class="balance-info">
              <span>当前余额：</span>
              <span :class="['balance', { 'insufficient': userBalance < totalAmount }]">
                ¥{{ userBalance.toFixed(2) }}
              </span>
            </p>
            <p v-if="userBalance < totalAmount" class="insufficient-warning">
              <el-icon><Warning /></el-icon>
              余额不足，请先充值
            </p>
          </div>
        </el-form-item>
        
        <el-form-item label="学校" prop="schoolId">
          <el-select v-model="taskForm.schoolId" placeholder="请选择学校" style="width: 100%">
            <el-option
              v-for="school in schools"
              :key="school.id"
              :label="school.name"
              :value="school.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="taskForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="taskForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="loading"
            :disabled="userBalance < totalAmount"
          >
            发布任务
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import api from '../../utils/api'
import { useUserStore } from '../../stores/user'

const router = useRouter()
const userStore = useUserStore()
const taskFormRef = ref()
const loading = ref(false)
const schools = ref([])

// 计算费用
const platformFee = computed(() => {
  return taskForm.reward * 0.03
})

const totalAmount = computed(() => {
  return taskForm.reward + platformFee.value
})

const userBalance = computed(() => {
  return userStore.user?.balance || 0
})

const calculateFees = () => {
  // 费用计算逻辑已在computed中处理
}

const taskForm = reactive({
  title: '',
  description: '',
  reward: 0,
  schoolId: '',
  startTime: '',
  endTime: ''
})

const taskRules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入任务描述', trigger: 'blur' }
  ],
  reward: [
    { required: true, message: '请输入奖励金额', trigger: 'blur' }
  ],
  schoolId: [
    { required: true, message: '请选择学校', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

const loadSchools = async () => {
  try {
    const response = await api.get('/auth/schools')
    if (response.data.code === 200) {
      schools.value = response.data.data
    }
  } catch (error) {
    console.error('加载学校列表失败:', error)
  }
}

const handleSubmit = async () => {
  if (!taskFormRef.value) return
  
  // 检查余额
  if (userBalance.value < totalAmount.value) {
    ElMessage.error('余额不足，请先充值')
    return
  }
  
  await taskFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await api.post('/user/tasks', {
          ...taskForm,
          startTime: taskForm.startTime ? new Date(taskForm.startTime).toISOString() : '',
          endTime: taskForm.endTime ? new Date(taskForm.endTime).toISOString() : ''
        })
        
        if (response.data.code === 200) {
          ElMessage.success('任务发布成功，已扣除相应费用')
          // 更新用户余额
          await userStore.fetchUserInfo()
          router.push('/user/published-tasks')
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('发布失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

const resetForm = () => {
  if (taskFormRef.value) {
    taskFormRef.value.resetFields()
  }
}

onMounted(() => {
  loadSchools()
})
</script>

<style scoped>
.new-task {
  padding: 20px;
}

.task-form {
  max-width: 600px;
}

.fee-info {
  margin-top: 10px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.fee-item {
  display: flex;
  justify-content: space-between;
  margin: 5px 0;
  font-size: 14px;
}

.fee-item.total {
  border-top: 1px solid #dee2e6;
  padding-top: 8px;
  margin-top: 8px;
  font-weight: bold;
}

.amount {
  color: #67c23a;
  font-weight: bold;
}

.fee {
  color: #e6a23c;
}

.total-amount {
  color: #f56c6c;
  font-weight: bold;
}

.balance-info {
  display: flex;
  justify-content: space-between;
  margin: 8px 0;
  font-size: 14px;
}

.balance {
  color: #67c23a;
  font-weight: bold;
}

.balance.insufficient {
  color: #f56c6c;
}

.insufficient-warning {
  display: flex;
  align-items: center;
  color: #f56c6c;
  font-size: 13px;
  margin: 8px 0 0 0;
}

.insufficient-warning .el-icon {
  margin-right: 5px;
}
</style>
